<template>
	<view class="order-fill">
		<!-- 顶部标题栏 -->
		<view class="header" :style="{ height: navBarHeight + 'px' }">
			<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
			<view class="nav-content" :style="{ height: menuButtonHeight + 'px' }">
				<view class="back-icon" @click="goBack">
					<text class="iconfont icon-ic_leftarrow"></text>
				</view>
				<view class="title">订单填写</view>
				<view class="placeholder" />
			</view>
		</view>

		<view class="main-content" :style="{ paddingTop: navBarHeight + 'px' }">
			<!-- 安全标签 -->
			<view class="safety-tag">
				<view class="tag-icon">✓</view>
				<text class="tag-text">配备智能门锁，入住更安心</text>
			</view>

			<!-- 房间信息 -->
			<view class="room-info">
				<view class="room-card">
					<image class="room-image" src="/static/images/f.png" mode="aspectFill"></image>
					<view class="room-detail">
						<view class="room-title">
							<text>{{ room.title }}</text>
							<view class="detail-arrow">房屋详情 ></view>
						</view>
						<view class="room-attributes">{{ room.roomType }}</view>
					</view>
				</view>

				<!-- 入住时间信息 -->
				<view class="stay-info">
					<!-- 添加日期选择区域 -->
					<view class="date-range" :class="{ 'active-date': isDateActive }" @click="openDatePicker">
						<view class="date-text">{{ formatDateRange }}</view>
						<view class="night-count">共{{ nightCount }}晚</view>
					</view>
					<view class="cancel-policy">
						<view class="policy-icon">○</view>
						<text>{{ cancelText }}</text>
						<view class="policy-space"></view>
						<view class="confirm-icon">○</view>
						<!-- <text class="confirm-text">立即确认</text> -->
					</view>
				</view>
			</view>

			<!-- 入住信息表单 -->
			<houseCheckinForm :formValue.sync="formData" @form-change="onFormChange" ref="checkinForm" />

			<!-- 优惠信息 -->
			<!-- <view class="discount-info">
				<view class="discount-tag">
					<text class="diamond-icon">💎</text>
					<text class="tag-text">钻石宾客 · 本单可享</text>
				</view>
				<view class="discount-detail">
					<text>下单优惠</text>
					<view class="price-info">
						<text class="discount-price">-¥620.00</text>
						<view class="discount-label">已享最大优惠</view>
						<text class="arrow-down">▼</text>
					</view>
				</view>
			</view> -->
		</view>

		<!-- 日期选择器 -->
		<uni-datetime-picker ref="datePicker" v-model="dateRange" type="daterange" :clear-icon="false" :start="minDate"
			:end="maxDate" @maskClick="closeDatePicker" @change="onDateChange" format="MM月DD日" :border="false"
			:insert="false" />

		<!-- 底部价格栏 -->
		<view class="bottom-bar">
			<view class="price-section">
				<view class="total-price-wrap">
					<text class="price-symbol">¥</text>
					<text class="total-price">{{ room.price }}</text>
					<!-- <text class="price-decimal">.00</text> -->
				</view>
				<!-- <text class="saved-price">已省¥620</text> -->
			</view>
			<view class="submit-button" @click="submitOrder">
				<text>提交订单</text>
				<view class="button-ripple"></view>
			</view>
		</view>
	</view>
</template>

<script>
import dayjs from '@/plugin/dayjs/dayjs.min.js'
import houseCheckinForm from '@/components/houseCheckinForm/index.vue';
import {
	getStoreRoomDetail
} from '@/api/store.js';
import {
	orderRoomCreate,
	orderPay
} from '@/api/order.js';
export default {
	components: {
		houseCheckinForm
	},
	data() {
		// 获取当前日期
		const today = dayjs().format('YYYY-MM-DD')
		const tomorrow = dayjs().add(1, 'day').format('YYYY-MM-DD')
		const nextYear = dayjs().add(1, 'year').format('YYYY-MM-DD')

		return {
			room: {},
			formData: {
				name: '',
				idCard: '',
				phone: ''
			},
			// 日期选择器相关
			isDateActive: false,
			dateRange: [today, tomorrow],
			minDate: today,
			maxDate: nextYear,
			// 其他数据
			basePrice: 690, // 每晚基础价格
			discountAmount: 620, // 优惠金额
			// 导航栏样式
			statusBarHeight: 0,
			navBarHeight: 0,
			menuButtonHeight: 0
		}
	},
	onLoad(options) {
		this.setNavStyle();
		this.id = options.room_id;
		this.getStoreRoomDetail();
		// 接收从详情页传递的日期参数
		const eventChannel = this.getOpenerEventChannel();
		const query = uni.getSystemInfoSync().platform === 'devtools' ?
			this.$mp.query : this.$mp?.query || {};

		if (query.checkInDate && query.checkOutDate) {
			// 如果有传入日期参数，则使用传入的参数
			const checkInDate = query.checkInDate;
			const checkOutDate = query.checkOutDate;

			// 将 MM-DD 格式转换为 YYYY-MM-DD 格式
			const year = new Date().getFullYear();
			this.dateRange = [
				`${year}-${checkInDate.replace('-', '-')}`,
				`${year}-${checkOutDate.replace('-', '-')}`
			];
		}
	},
	computed: {
		// 取消政策文本
		cancelText() {
			if (this.dateRange && this.dateRange.length === 2) {
				const checkInDate = dayjs(this.dateRange[0])
				const month = checkInDate.format('M')
				const day = checkInDate.format('D')
				return `${month}月${day}日18:00前可免费取消`
			}
			return '入住前可免费取消'
		},
		formatDateRange() {
			if (this.dateRange && this.dateRange.length === 2) {
				const checkInDate = dayjs(this.dateRange[0])
				const checkOutDate = dayjs(this.dateRange[1])
				const checkInMonth = checkInDate.format('MM')
				const checkInDay = checkInDate.format('DD')
				const checkOutMonth = checkOutDate.format('MM')
				const checkOutDay = checkOutDate.format('DD')
				const checkInWeek = this.getWeekDay(checkInDate.day())
				const checkOutWeek = this.getWeekDay(checkOutDate.day())
				return `${checkInMonth.replace(/^0/, '')}月${checkInDay.replace(/^0/, '')}日${checkInWeek} - ${checkOutMonth.replace(/^0/, '')}月${checkOutDay.replace(/^0/, '')}日${checkOutWeek}`
			}
			return '选择入住日期'
		},
		nightCount() {
			if (this.dateRange && this.dateRange.length === 2) {
				const checkInDate = dayjs(this.dateRange[0])
				const checkOutDate = dayjs(this.dateRange[1])
				return checkOutDate.diff(checkInDate, 'day')
			}
			return 0
		}
	},
	methods: {
		getStoreRoomDetail() {
			getStoreRoomDetail(this.id).then(res => {
				this.room = res.data;
				// 根据接口返回的bookingDate字段设置dateRange
				if (res.data.bookingDate && Array.isArray(res.data.bookingDate) && res.data.bookingDate.length === 2) {
					this.dateRange = res.data.bookingDate;
				}
			});
		},
		// 返回上一页
		goBack() {
			uni.navigateBack();
		},
		// 获取星期几
		getWeekDay(day) {
			const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
			return weekDays[day];
		},
		// 打开日期选择器
		openDatePicker() {
			this.isDateActive = true;
			if (this.$refs.datePicker) {
				this.$refs.datePicker.open();
			}
		},
		// 日期选择器关闭
		closeDatePicker() {
			this.isDateActive = false;
		},
		// 日期变更处理
		onDateChange(e) {
			this.dateRange = e;
			this.isDateActive = false;
		},
		// 表单数据变化处理
		onFormChange(data) {
			console.log('表单数据变化:', data);
			// 可以在这里处理表单数据变化的逻辑
		},

		// 提交订单
		submitOrder() {
			// 表单验证
			if (!this.formData.name) {
				uni.showToast({
					title: '请填写住客姓名',
					icon: 'none'
				})
				return
			}

			// 简单身份证号校验（可根据实际需求调整正则）
			const idCardReg = /^(\d{15}|\d{17}[\dXx])$/;
			if (!this.formData.idCard) {
				uni.showToast({
					title: '请填写证件号码',
					icon: 'none'
				})
				return
			} else if (!idCardReg.test(this.formData.idCard)) {
				uni.showToast({
					title: '证件号码格式不正确',
					icon: 'none'
				})
				return
			}

			// 手机号校验（中国大陆手机号）
			const phoneReg = /^1[3-9]\d{9}$/;
			if (!this.formData.phone) {
				uni.showToast({
					title: '请填写联系电话',
					icon: 'none'
				})
				return
			} else if (!phoneReg.test(this.formData.phone)) {
				uni.showToast({
					title: '联系电话格式不正确',
					icon: 'none'
				})
				return
			}

			// 其他校验可按需添加

			uni.showToast({
				title: '订单提交中',
				icon: 'loading'
			})

			// 组装订单数据
			const orderData = {
				room_id: this.room.id,
				amount: this.room.price,
				name: this.formData.name,
				idCard: this.formData.idCard,
				phone: this.formData.phone,
				dateRange: this.dateRange,
				mer_id: this.room.mer_id
			};

			// 先创建订单
			orderRoomCreate(orderData).then(res => {
				const orderId = res.data.configs.order_id;
				console.log(orderId,res)
				if (!orderId) {
					uni.showToast({ title: '订单创建失败', icon: 'none' });
					return;
				}
				var payData = res.data.configs.config;
				// 调用支付接口，获取微信支付参数
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: payData.timestamp,
					nonceStr: payData.nonceStr,
					package: payData.package,
					signType: payData.signType,
					paySign: payData.paySign,
					success: () => {
						uni.showToast({ title: '支付成功', icon: 'success' });
						// uni.redirectTo({ url: '/pages/order/pay_result?order_id=' + orderId });
					},
					fail: () => {
						uni.showToast({ title: '支付失败', icon: 'none' });
					}
				});
			}).catch(() => {
				uni.showToast({ title: '订单创建失败', icon: 'none' });
			});
		},
		// 设置导航栏样式
		setNavStyle() {
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight || 0;

			// #ifdef MP-WEIXIN
			const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
			this.menuButtonHeight = menuButtonInfo.height;
			this.navBarHeight = this.statusBarHeight + menuButtonInfo.height + (menuButtonInfo.top - this
				.statusBarHeight) * 2;
			// #endif

			// #ifndef MP-WEIXIN
			this.menuButtonHeight = 44;
			this.navBarHeight = this.statusBarHeight + 44;
			// #endif
		}
	}
}
</script>

<style lang="scss" scoped>
.order-fill {
	position: relative;
	padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
	background-color: #f8f4ef;
	min-height: 100vh;
	box-sizing: border-box;
}

/* 头部样式 */
.header {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	background-color: #fff8f4;
	z-index: 99;

	.status-bar {
		width: 100%;
	}

	.nav-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;

		.back-icon {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.iconfont {
				font-size: 40rpx;
				color: #333;
			}
		}

		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}

		.placeholder {
			width: 60rpx;
		}
	}
}

.main-content {
	/* 主体内容样式 */
}

/* 安全标签 */
.safety-tag {
	margin: 20rpx;
	display: flex;
	align-items: center;
	padding: 12rpx 20rpx;
	border-radius: 100rpx;
	background-color: #efffef;
	border: 1px solid #b7f1b7;
	width: fit-content;

	.tag-icon {
		color: #fff;
		background: #07c160;
		border-radius: 50%;
		width: 32rpx;
		height: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20rpx;
		margin-right: 10rpx;
	}

	.tag-text {
		color: #07c160;
		font-size: 26rpx;
	}
}

/* 房间信息 */
.room-info {
	margin: 20rpx;
	background-color: white;
	border-radius: 24rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

	.room-card {
		display: flex;
		padding: 30rpx;
		border-bottom: 1rpx solid #f5f5f5;

		.room-image {
			width: 120rpx;
			height: 120rpx;
			border-radius: 10rpx;
			margin-right: 20rpx;
			background-color: #f0f0f0;
		}

		.room-detail {
			flex: 1;

			.room-title {
				display: flex;
				justify-content: space-between;
				font-size: 30rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;

				.detail-arrow {
					color: #999;
					font-size: 26rpx;
					font-weight: normal;
				}
			}

			.room-attributes {
				color: #666;
				font-size: 26rpx;
			}
		}
	}

	.stay-info {
		padding: 30rpx;

		/* 增强点击区域的可点击性 */
		&:active {
			background-color: rgba(0, 0, 0, 0.03);
		}

		.date-range {
			display: flex;
			justify-content: space-between;
			font-size: 30rpx;
			color: #333;
			margin-bottom: 20rpx;
			padding: 20rpx 0;
			position: relative;
			transition: all 0.2s ease;

			&.active-date {
				background-color: rgba(255, 96, 52, 0.05);
				border-radius: 8rpx;
			}

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 0;
				width: 100%;
				height: 2rpx;
				background-color: transparent;
				transition: background-color 0.3s;
			}

			&:active::after {
				background-color: #ff6034;
			}

			.date-text {
				color: #333;
				font-size: 28rpx;
				font-weight: 500;
			}

			.night-count {
				color: #999;
				font-size: 26rpx;
			}
		}

		.cancel-policy {
			display: flex;
			align-items: center;
			font-size: 26rpx;
			color: #666;

			.policy-icon {
				color: #07c160;
				border: 1px solid #07c160;
				border-radius: 50%;
				width: 24rpx;
				height: 24rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 16rpx;
				margin-right: 10rpx;
			}

			.policy-space {
				flex: 1;
				min-width: 20rpx;
			}

			.confirm-icon {
				color: #07c160;
				border: 1px solid #07c160;
				border-radius: 50%;
				width: 24rpx;
				height: 24rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 16rpx;
				margin-right: 10rpx;
			}

			.confirm-text {
				color: #333;
			}
		}
	}
}

/* 入住信息表单样式已移至组件 */

/* 优惠信息 */
.discount-info {
	margin: 20rpx;
	background-color: white;
	border-radius: 24rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

	.discount-tag {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #f8f2ff;

		.diamond-icon {
			margin-right: 10rpx;
			font-size: 32rpx;
			color: #8a2be2;
		}

		.tag-text {
			color: #8a2be2;
			font-size: 28rpx;
		}
	}

	.discount-detail {
		display: flex;
		justify-content: space-between;
		padding: 30rpx;
		align-items: center;

		color: #333;
		font-size: 28rpx;

		.price-info {
			display: flex;
			align-items: center;

			.discount-price {
				color: #ff4500;
				font-weight: bold;
				font-size: 30rpx;
			}

			.discount-label {
				color: #ff4500;
				font-size: 22rpx;
				background-color: #ffece5;
				padding: 4rpx 10rpx;
				border-radius: 6rpx;
				margin: 0 10rpx;
			}

			.arrow-down {
				color: #999;
				font-size: 24rpx;
			}
		}
	}
}

/* 底部价格栏 */
.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	height: 120rpx;
	background-color: white;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	/* 增加安全区域适配 */
	padding-bottom: env(safe-area-inset-bottom);
	box-sizing: content-box;
	z-index: 99;

	.price-section {
		display: flex;
		flex-direction: column;
		justify-content: center;

		.total-price-wrap {
			display: flex;
			align-items: baseline;

			.price-symbol {
				color: #ff4500;
				font-size: 30rpx;
				font-weight: bold;
			}

			.total-price {
				color: #ff4500;
				font-size: 52rpx;
				font-weight: bold;
				line-height: 1;
			}

			.price-decimal {
				color: #ff4500;
				font-size: 30rpx;
				font-weight: bold;
			}
		}

		.saved-price {
			color: #ff4500;
			font-size: 26rpx;
			margin-top: 6rpx;
		}
	}

	.submit-button {
		background: linear-gradient(135deg, #ff7a52, #ff6034);
		color: white;
		padding: 24rpx 64rpx;
		border-radius: 100rpx;
		font-size: 32rpx;
		font-weight: bold;
		box-shadow: 0 4rpx 12rpx rgba(255, 96, 52, 0.3);
		transition: transform 0.2s ease;
		position: relative;
		overflow: hidden;
		display: flex;
		justify-content: center;
		align-items: center;

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2rpx 8rpx rgba(255, 96, 52, 0.2);
		}

		.button-ripple {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: radial-gradient(circle, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 70%);
			transform: scale(0);
			opacity: 0;
			pointer-events: none;
		}

		&:active .button-ripple {
			animation: ripple 0.6s ease-out;
		}
	}
}

@keyframes ripple {
	0% {
		transform: scale(0);
		opacity: 0.5;
	}

	100% {
		transform: scale(2);
		opacity: 0;
	}
}

/* 日期选择器样式覆盖 */
:deep(.uni-datetime-picker) {
	.uni-datetime-picker-container {
		border-radius: 24rpx;
		overflow: hidden;
	}

	.uni-datetime-picker-btn {
		padding: 20rpx;
		font-size: 32rpx;
	}

	.uni-datetime-picker-btn-text {
		font-size: 32rpx;
	}

	.uni-calendar-item__weeks-box {
		font-size: 30rpx;
	}

	.uni-calendar-item--checked {
		background-color: #ff6034;
	}

	.uni-calendar-item--checked-range-text {
		color: #ff6034;
	}

	.uni-calendar-item--checked-range {
		background-color: rgba(255, 96, 52, 0.1);
	}
}
</style>